package com.example.choupaiapp.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ActivityManager;
import com.example.choupaiapp.common.util.GsonUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.activity.find.FindBannerWebviewActivity;
import com.example.choupaiapp.main.bean.QQLoginBean;
import com.example.choupaiapp.main.bean.QQLoginUserInfoBean;
import com.example.choupaiapp.main.bean.TokenBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.callback.WechatCallBack;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.util.QQLoginUtil;
import com.example.choupaiapp.main.util.WechatLoginUtil;
import com.example.choupaiapp.main.util.WeiboLoginUtil;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by ASUS on 2019/10/29.
 */

public class PasswordLoginActivity extends CommonActivity {

    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.cb_check)
    AppCompatCheckBox cbCheck;
    @BindView(R.id.next)
    TextView next;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_password_login);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);

        findView(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                if (cbCheck.isChecked()) {
                    EventBus.getDefault().post("agree_agreedment");
                } else {
                    EventBus.getDefault().post("refuse_agreedment");
                }
                finishActivity();
            }
        });

        cbCheck.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                if (phone.getText().toString().length() == 11) {
                    if (password.getText().toString().length() >= 6) {
                        next.setEnabled(true);
                    } else {
                        next.setEnabled(false);
                    }
                } else {
                    next.setEnabled(false);
                }
            } else {
                next.setEnabled(false);
            }
        });

        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() == 11) {
                    if (cbCheck.isChecked()) {
                        if (password.getText().toString().length() >= 6) {
                            next.setEnabled(true);
                        } else {
                            next.setEnabled(false);
                        }
                    } else {
                        next.setEnabled(false);
                    }
                } else {
                    next.setEnabled(false);
                }
            }
        });

        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().length() >= 6) {
                    if (cbCheck.isChecked()) {
                        if (phone.getText().toString().length() == 11) {
                            next.setEnabled(true);
                        } else {
                            next.setEnabled(false);
                        }
                    } else {
                        next.setEnabled(false);
                    }
                } else {
                    next.setEnabled(false);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onBackPressed() {
        if (cbCheck.isChecked()) {
            EventBus.getDefault().post("agree_agreedment");
        } else {
            EventBus.getDefault().post("refuse_agreedment");
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.contains("agree_agreedment")) {
            cbCheck.setChecked(true);
        } else if (event.contains("refuse_agreedment")) {
            cbCheck.setChecked(false);
        }
    }


    //    @Override
    @OnClick({R.id.cb_check, R.id.agreement, R.id.next, R.id.password_login})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.cb_check:
                break;
            case R.id.agreement:
                Bundle bundle = new Bundle();
                bundle.putString("url", "http://app.tisuapp.com/app-web/html/iosAgreement.html");
                startActivity(FindBannerWebviewActivity.class, bundle);
                break;
            case R.id.next:
                if (cbCheck.isChecked()) {
                    if (phone.getText().toString().startsWith("1")) {
                        if (phone.getText().toString().length() == 11) {
                            showDialog(this, "登录中...");
                            HttpParams params = new HttpParams();
                            params.put("mobile", phone.getText().toString().trim());
                            params.put("password", password.getText().toString().trim());
                            finalOkGo.request(RequestType.POST, Url.PASSWORD_LOGIN, params, Url.PASSWORD_LOGIN, new Callback<TokenBean>() {
                                @Override
                                public void onSuccess(TokenBean tokenBean) {
                                    if (tokenBean.getCode() == Contacts.SUCCESS) {
                                        SharedPreferencesHelp.put("token", tokenBean.getToken());
                                        finalOkGo.requestHead(RequestType.GETHEAD, Url.GET_UERINFO, null, Url.GET_UERINFO, new Callback<UserInfoBean>() {
                                            @Override
                                            public void onSuccess(UserInfoBean userInfoBean) {
                                                if (userInfoBean.getCode() == Contacts.SUCCESS) {
                                                    SharedPreferencesHelp.putBean("userInfo", userInfoBean);
                                                    CrashReport.setUserId(context, userInfoBean.getUser().getMobile());
                                                    EMClient.getInstance().login("HX_" + userInfoBean.getUser().getUserId(), "HX_" + userInfoBean.getUser().getUserId(), new EMCallBack() {//回调
                                                        @Override
                                                        public void onSuccess() {
                                                            dismissDialog();
                                                            EMClient.getInstance().groupManager().loadAllGroups();
                                                            EMClient.getInstance().chatManager().loadAllConversations();
                                                            JPushInterface.setAlias(context, 0, Config.JPUS_PRE + userInfoBean.getUser().getUserId());
                                                            ActivityManager.getActivityManager().popAllActivity();
                                                            startFinishActivity(MainActivity.class);
                                                        }

                                                        @Override
                                                        public void onProgress(int progress, String status) {

                                                        }

                                                        @Override
                                                        public void onError(int code, final String message) {
                                                            runOnUiThread(() -> {
                                                                Logger.e(code + ":" + message);
                                                                dismissDialog();
                                                                JPushInterface.setAlias(context, 0, Config.JPUS_PRE + userInfoBean.getUser().getUserId());
                                                                showImageToas("即时通讯登录失败 私信功能不能使用");
                                                                ActivityManager.getActivityManager().popAllActivity();
                                                                startFinishActivity(MainActivity.class);
                                                            });

                                                        }
                                                    });
                                                } else {
                                                    dismissDialog();
                                                    if (userInfoBean.getCode() == Contacts.TOKEN_EMPTY) {
                                                    } else {
                                                        showImageToas(userInfoBean.getMsg());
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onError(Response<String> response) {
                                                super.onError(response);
                                                dismissDialog();
                                            }
                                        });
                                    } else {
                                        dismissDialog();
                                        if (tokenBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        } else {
                                            showImageToas(tokenBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                }
                            });
                        } else {
                            showImageToas("请输入正确的手机号");
                        }
                    } else {
                        showImageToas("请输入正确的手机号");
                    }
                } else {
                    showImageToas("请勾选丑拍使用协议");
                }

                break;
            case R.id.password_login:
                if (cbCheck.isChecked()) {
                    EventBus.getDefault().post("agree_agreedment");
                } else {
                    EventBus.getDefault().post("refuse_agreedment");
                }
                finishActivity();
                break;

        }
    }


}
